import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Injector, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ActivatedRoute, Params } from '@angular/router';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import {
    AddNewPaperInput,
    GetWorkFlowInfoOutput,
    PagedPaperInput,
    ThemeHeaderSettingsDto,
    WorkFlowManagerServiceProxy,
    WorkFlowQueryServiceProxy,
    WorkFlowServiceProxy
} from '@shared/service-proxies/service-proxies';
import { LazyLoadEvent } from 'primeng/api';
import { Paginator } from 'primeng/paginator';
import { Table } from 'primeng/table';
import { finalize } from 'rxjs/operators';
import { DateTime } from 'luxon';
import { DateTimeService } from '@app/shared/common/timing/date-time.service';
import { TabDirective } from 'ngx-bootstrap/tabs';
import { WorkflowDetailComponent } from '../workflow-detail.component';
import { IActionNames, IBackWorkFlowListData, IFlowDetailParam } from '@app/shared/common/workflow/workflow-common-interface';

@Component({
    templateUrl: './workflow-recruitment-list.component.html',
    animations: [appModuleAnimation()]
})
export class WorkFlowRecruitmentListComponent extends AppComponentBase {

    @ViewChild('dataTable', { static: true }) dataTable: Table;
    @ViewChild('paginator', { static: true }) paginator: Paginator;

    @ViewChild('workFlowDetail', { static: true }) workflowDetailModal: WorkflowDetailComponent;
    advancedFiltersAreShown = false;
    filterText = '';
    kind: number;
    workFlowId: string = '8f1ed13d-5846-4e36-f9c6-08d9a71ef447';
    canCreateNew = false;

    createNewData?: GetWorkFlowInfoOutput

    actionNames = [
        {"name":'草稿','isShow':false,"type":0},
        { "name": '待办', 'isShow': true,"type":1 },
        { "name": '在办', 'isShow': true,"type":2 },
        { "name": '办结', 'isShow': true,"type":3 }
    ]

    pagedPaperParam: PagedPaperInput = new PagedPaperInput();
    constructor(
        injector: Injector,
        private _activatedRoute: ActivatedRoute,
        private _workFlowQueryServiceProxy: WorkFlowQueryServiceProxy,
        private _workFlowServiceProxy: WorkFlowServiceProxy,
        private _workFlowManagerServiceProxy:WorkFlowManagerServiceProxy,
        private _dateTimeService: DateTimeService,
        public changeDetectorRef:ChangeDetectorRef 
    ) {
        super(injector);
        this.pagedPaperParam.wfQueryType = 1;
        this.pagedPaperParam.fieldList = ["当前审核状态"];
        this.pagedPaperParam.inclusiveWorkFlowId = [this.workFlowId];
    }

    ngOnInit() {
        this._activatedRoute.params.subscribe((params: Params) => {
            this.kind = Number(params['kind']);
            this.init();
        });
    }

    init(){
        this._workFlowServiceProxy.getWorkFlowInfo(this.workFlowId).subscribe((result)=>{
            if (result.name){
                this.canCreateNew = true;
                this.actionNames[0].isShow = this.canCreateNew;
                this.actionNames = this.actionNames.filter(x=>x.isShow);
                this.createNewData = result
            }
            else{
                this.actionNames = this.actionNames.filter(x=>x.isShow);
            }
        });
    }

    getListData(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            if (this.primengTableHelper.TryChangePage(this.paginator, 0)) {
                return;
            }
        }
        this.primengTableHelper.showLoadingIndicator();
        this.pagedPaperParam.filter = this.filterText;
        this.pagedPaperParam.sorting = this.primengTableHelper.getSorting(this.dataTable);
        this.pagedPaperParam.maxResultCount = this.primengTableHelper.getMaxResultCount(this.paginator, event);
        this.pagedPaperParam.skipCount = this.primengTableHelper.getSkipCount(this.paginator, event);
        this._workFlowQueryServiceProxy.getPagedPapers(this.pagedPaperParam).pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
            this.primengTableHelper.totalRecordsCount = result.totalCount;
            this.primengTableHelper.records = result.items;
            this.primengTableHelper.hideLoadingIndicator();
        });
    }

    deleteWorkFlow(id: string): void {
        this.message.confirm(this.l('DeleteWarningMessage'), this.l('AreYouSure'),
            (isConfirmed) => {
                if (!isConfirmed) return;
                this._workFlowManagerServiceProxy.delete([id])
                    .subscribe(() => {
                        this.reloadPage();
                        this.notify.success(this.l('SuccessfullyDeleted'));
                    });
            })
    }

    reloadPage() {
        if (this.primengTableHelper.TryChangePage(this.paginator, this.paginator.getPage())) {
            return;
        }

        this.getListData(null);
    }

    create(){
        if (this.createNewData) {
            let date = this._dateTimeService.getDate();
            let newTitle = this.createNewData.defaultTitle
                .replace("{流程名}", this.createNewData.name)
                .replace("{流程简称}", this.createNewData.shortName)
                .replace("{用户姓名}", abp.custom.oaUser.userName)
                .replace("{用户部门}", abp.custom.oaUser.mainOrgnzation.name)
                .replace("{年}", date.toFormat('yyyy'))
                .replace("{月}", date.toFormat('MM'))
                .replace("{日}", date.toFormat('dd'))
                .replace("{时}", date.toFormat('HH'))
                .replace("{分}", date.toFormat('mm'))
                .replace("{秒}", date.toFormat('ss'));
                
            if (!this.workFlowId || !newTitle) {
                return;
            }

            this._workFlowServiceProxy.addNewPaper(new AddNewPaperInput({
                workFlowId: this.workFlowId,
                title: newTitle
            })).subscribe(result => {
                this.openDetail({ paperId: result });
            });
        }
    }


    goDetailModel(id:string) {
        this.openDetail({ paperId: id });
    }


    openDetail(item: IFlowDetailParam) {
        this.workflowDetailModal.show(item);
    }


    backToList(item?: IBackWorkFlowListData) {
        if (item && item.isReload){
            this.pagedPaperParam.wfQueryType = 1;
            if (this.primengTableHelper.TryChangePage(this.paginator, 0)) {
                return;
            }

            this.getListData(null);
        }
    }

    private changeTab(index: number) {
        this.pagedPaperParam.wfQueryType = this.actionNames[index].type;

        if (this.primengTableHelper.TryChangePage(this.paginator, 0)) {
            return;
        }

        this.getListData(null);
    }

    onTabSelect(data: TabDirective, index: number) {
        this.changeTab(index);
    }
}


